package com.atguigu.srb.oss.controller.api;

import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.oss.Service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

@Api(tags= "阿里云管理")
//@CrossOrigin
@RestController
@RequestMapping("/api/oss/file")
public class OssController {


    @Resource
    OssService ossService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R upload(@ApiParam(value = "要传输的文件",required = true)
                    @RequestParam("file")MultipartFile multipartFile,
                    @ApiParam(value = "模块",required = true)
                    @RequestParam("module") String module){

        try {
            String originalFilename = multipartFile.getOriginalFilename();
            InputStream inputStream = multipartFile.getInputStream();
            String uploda = ossService.uploda(inputStream, module, originalFilename);
         return R.ok().message("上传文件成功").data("url",uploda);
        } catch (IOException e) {
           throw  new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    @ApiOperation("删除OSS文件")
    @DeleteMapping("/remove")
    public R remove(
            @ApiParam(value = "要删除的文件路径", required = true)
            @RequestParam("url") String url) {
        ossService.removeFile(url);
        return R.ok().message("删除成功");
    }
}
